package comment

import (
	"dog-blog/app/post/models"
	"dog-blog/app/post/resp"
	"dog-blog/app/post/services"
	"dog-blog/base/apis"
	"fmt"
	"regexp"

	"github.com/gin-gonic/gin"
)

type Comment struct {
	apis.Api
}

// CreateComment 创建一条数据
func (e Comment) CreateComment(c *gin.Context) {
	e.Context = c

	comment := new(models.Comment)

	err := comment.Bind(c)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	if len(comment.Content) > 512 {
		e.Default(resp.ErrCommentConent)
	}

	if len(comment.UserName) > 64 {
		e.Default(resp.ErrCommentNick)
	}

	if !regexp.MustCompile(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`).MatchString(comment.Email) {
		e.Default(resp.ErrCommentEmail)
	}

	isOk := services.SaveComment(*comment)

	if isOk {
		e.Default(resp.OK)
	} else {
		e.Default(resp.ERR)
	}
}

// GetAllComment 返回所有的 todo 数据
func (e Comment) GetAllComment(c *gin.Context) {
	e.Context = c

	commentPageReq := new(models.CommentPageReq)

	err := commentPageReq.Bind(c)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	if commentPageReq.PageNum < 1 {
		e.Default(resp.ErrParam)
		return
	}

	pageData, isOk := services.FindComments(commentPageReq)

	if isOk {
		result := resp.CommentPageResp{BaseResp: resp.BaseResp{ErrCode: resp.OK, ErrDesc: resp.ErrDesc[resp.OK]}}
		result.Data = pageData
		e.Custom(result)
	} else {
		e.Default(resp.OK)
	}
}

// GetComment 方法 获取 todo 数据
func (e Comment) GetComment(c *gin.Context) {
}

// UpdateComment 方法 更新 todo 数据
func (e Comment) UpdateComment(c *gin.Context) {
}

// DeleteComment 方法依据 id 删除一条todo 数据
func (e Comment) DeleteComment(c *gin.Context) {
}
